import os

import cv2
import numpy as np
from tqdm import tqdm

from option import parse_args


def videos_mean(diffs_path, func, template: str, args, mask_lower_threshold=0., mask_upper_threshold=0.):
    video_names = os.listdir(diffs_path)
    video_names.sort()
    t = tqdm(video_names) if args.save else video_names
    for video_name in t:
        mean_min, mean_max = 255., 0.
        video_path = os.path.join(diffs_path, video_name)
        count_less_equal_than = 0
        count_more_equal_than = 0
        for diff in os.listdir(video_path):
            mask = cv2.imread(os.path.join(video_path, diff), cv2.IMREAD_GRAYSCALE)
            mean_min = min(mean_min, np.mean(mask))
            mean_max = max(mean_max, np.mean(mask))
            if np.mean(mask) <= mask_lower_threshold:
                count_less_equal_than += 1
            if np.mean(mask) >= mask_upper_threshold:
                count_more_equal_than += 1
        # sub = mean_max - mean_min
        if mean_min <= mask_lower_threshold or mean_max >= mask_upper_threshold:
            func(template.format(video_name, mean_min, mean_max, count_less_equal_than, count_more_equal_than))


def main():
    args = parse_args()
    version = args.compression_version
    # original_crops = os.path.join(args.root_dir, 'original_sequences', 'youtube', 'c23', 'crops')
    manipulated_path = os.path.join(args.root_dir, 'manipulated_sequences')
    args.save = True
    for fake_type in os.listdir(manipulated_path):
        print(fake_type)
        manipulation_type_path = os.path.join(manipulated_path, fake_type)
        manipulation_diffs_path = os.path.join(manipulation_type_path, version, 'diffs')
        if args.save:
            with open(f'abnormal_mean_statistics_{fake_type}_{version}.dat', 'w') as f:
                videos_mean(manipulation_diffs_path, f.write, '{},{:.2f},{:.2f},{},{}\n', args,
                            mask_lower_threshold=10., mask_upper_threshold=50.)
        else:
            videos_mean(manipulation_diffs_path, print, '{},{:.2f},{:.2f},{},{}', args,
                        mask_lower_threshold=10., mask_upper_threshold=50.)


if __name__ == '__main__':
    main()
